<?php


namespace App\Common\Business;

use App\Common\Model\Users as UsersModel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class Users
{
    public $model;
    public function __construct()
    {
        $this->model = new UsersModel();
    }

    public function listsTree($id = '')
    {
        if ($id) {
            return $this->model->where('id', $id)
                ->with('childrenUsers')
                ->get();
        }
        return $res = $this->model->whereNull('pid')
            ->with('childrenUsers')
            ->get();
    }

    public function listsTree2()
    {
        $users = $this->model->select('id as u_id', 'pid', 'name', 'mrp_code')->get()->toArray();
        $users = \App\Common\Lib\Arr::getTree($users);
        return $users;
    }

    public function register($data)
    {
        if (empty($data)) {
            return false;
        }

        DB::beginTransaction();
        try {
            if ($data['mrp_code']) {
                $data['pid'] = $this->model->where('mrp_code',$data['mrp_code'])->pluck('id')[0];
            }
            $data['mrp_code'] = \App\Common\Lib\MrpCode::createCode();
            $id = $this->model->insertGetId($data);

            // 如邀请码存在更新推荐人积分
            if (isset($data['pid'])) {
                $this->updateReferrerMrf($data['pid']);
            }
            DB::commit();
        } catch (\Exception $e) {
            Log::error('注册用户失败'.$e->getMessage());
            DB::rollBack();
            return false;
        }
        return true;
    }

    // 更新推荐人的积分(只更新上2层父类的积分)
    public function updateReferrerMrf($pid)
    {
        if (!$pid) {
            return false;
        }
        $time = time();
        $p1 = $this->model->where('id', $pid)->first(['id', 'pid']);
        $mrpConfig = (new \App\Common\Model\MrpConfig)->pluck('num', 'lv');
        $this->model->where('id', $pid)->increment('mrp', $mrpConfig[1]);
        $mrpChangeData[] = ['uid' => $pid, 'change_num' => $mrpConfig[1], 'created_at'=>$time];

        if ($this->model->where('id', $p1['pid'])->exists()) {
            $p2 = $this->model->where('id', $p1['pid'])->first(['id', 'pid']);
            $mrpChangeData[] = ['uid' => $p2['pid'], 'change_num' => $mrpConfig[2], 'created_at'=>$time];
            $this->model->where('id', $p2['pid'])->increment('mrp', $mrpConfig[2]);
        }
        (new \App\Common\Model\MrpChangeLog())->insert($mrpChangeData);
    }

}
